package com.yatoooon.screenadaptation.loadviewhelper;

import com.yatoooon.screenadaptation.conversion.IConversion;
import com.yatoooon.screenadaptation.conversion.SimpleConversion;
import com.yatoooon.screenadaptation.utils.ActualScreen;

import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.app.Context;

/**
 * AbsLoadViewHelper;
 *
 * @since 2021-04-13
 */
public abstract class AbsLoadViewHelper implements ILoadViewHelper {
    private static final int INT4 = 4;
    private static final int INT2 = 2;
    private static final int INT3 = 3;
    protected float actualDensity;
    protected float actualDensityDpi;
    protected float actualWidth;
    protected float actualHeight;

    protected int designWidth;
    protected int designDpi;
    protected float fontSize;
    protected String unit;

    /**
     * AbsLoadViewHelper
     *
     * @param context
     * @param designWidth
     * @param designDpi
     * @param fontSize
     * @param unit
     */
    public AbsLoadViewHelper(Context context, int designWidth, int designDpi, float fontSize, String unit) {
        this.designWidth = designWidth;
        this.designDpi = designDpi;
        this.fontSize = fontSize;
        this.unit = unit;
        setActualParams(context);
    }

    /**
     * reset
     *
     * @param context
     */
    public void reset(Context context) {
        setActualParams(context);
    }

    private void setActualParams(Context context) {
        float[] actualScreenInfo = ActualScreen.screenInfo(context);
        if (actualScreenInfo.length == INT4) {
            actualWidth = actualScreenInfo[0];
            actualHeight = actualScreenInfo[1];
            actualDensity = actualScreenInfo[INT2];
            actualDensityDpi = actualScreenInfo[INT3];
        }
    }

    /**
     * loadView
     *
     * @param component
     */
    public void loadView(Component component) {
        loadView(component, new SimpleConversion());
    }

    /**
     * loadView
     *
     * @param view
     * @param conversion
     */
    public final void loadView(Component view, IConversion conversion) {
        if (view instanceof ComponentContainer) {
            ComponentContainer viewGroup = (ComponentContainer) view;
            conversion.transform(viewGroup, this);
            for (int i = 0; i < viewGroup.getChildCount(); i++) {
                if (viewGroup.getComponentAt(i) instanceof ComponentContainer) {
                    loadView(viewGroup.getComponentAt(i), conversion);
                } else {
                    conversion.transform(viewGroup.getComponentAt(i), this);
                }
            }
        } else {
            conversion.transform(view, this);
        }
    }
}
